Repository navigation
refactor: centralize initial workspace selection for system pages - #8292
Conversation
|
|
||
| return workspaceList?.find((workspace) => workspace.id && hasWorkspaceManagerRole(workspace))?.id ?? 'default' | ||
| return firstManagedWorkspaceId ?? 'default' | ||
| } |
There was a problem hiding this comment.
Here's my review of the diff:
Irregularities / Potential Issues
-
preferredWorkspaceIdis typed asstring | nullimplicitly but declared withletand reassigned tonull— TypeScript may infer the type fromlocalStorage.getItem(...)which returnsstring | null. That's fine, but the mutation (preferredWorkspaceId = null) inside the loop makes the logic harder to follow than necessary. Consider a clearer variable naming (e.g.,cachedWorkspaceId, keep the original signature). -
Early-return micro-optimization is fragile.
if (!preferredWorkspaceId && firstManagedWorkspaceId) return firstManagedWorkspaceIdThis runs at the end of every iteration. It works, but it relies on the invariant that once the cached ID is cleared, the first managed workspace has already been captured. If the loop order or the meaning of "first" changes later, this becomes a subtle bug source. A cleaner structure: collect firstManagedWorkspaceId in one pass, then decide at the end.
-
Behavioral change: the function signature changed from
(cachedWorkspaceId, workspaceList)to(workspaceList?). The function now reads fromlocalStoragedirectly. This:- Makes it impure / harder to unit test (requires mocking
localStorage). - Couples a pure selection utility to storage. Previously callers could inject the cached value. Recommend keeping the cache read in the caller and keeping this function pure — arguably the biggest regression here.
- Verify all call sites were updated; any caller still passing two args will silently ignore the second argument (no TS error if the second value is compatible... actually TS would error on arity). Confirm callers.
- Makes it impure / harder to unit test (requires mocking
-
ADMIN_STORAGE_KEY.WORKSPACE_IDscope assumption. Reading globallocalStorageassumes browser environment (no SSR guard). If this module can run server-side, this throwsReferenceError. Consider a guard or injection. -
Duplicate
role_infolookup logic —hasWorkspaceManagerRolewas removed and inlined. That loses the named helper's readability/reuse. Minor, but the inline check appears once, so acceptable; just note it reduces future reuse. -
Empty-string
idhandling —if (!id) continueskips empty IDs, good. But for the cached branch, ifid === preferredWorkspaceIdwhere both are''...preferredWorkspaceIdcan't be''unless stored; edge case, low risk. -
'default'fallback semantics unchanged, fine.
Optimization Suggestions
- Revert to a pure function taking
cachedWorkspaceIdas a parameter (better testability and separation of concerns), or at minimum wrap localStorage access behind a safe helper. - Restructure to a single clear flow:
export function getInitialWorkspaceId(
cachedWorkspaceId: string | null,
workspaceList?: WorkspaceItem[],
): string {
const managed = (workspaceList ?? []).filter(
({ id, role_info }) =>
id && role_info?.some(({ role_type }) => role_type === ROLE_TYPE.WORKSPACE_MANAGE),
)
if (cachedWorkspaceId && managed.some(({ id }) => id === cachedWorkspaceId)) {
return cachedWorkspaceId
}
return managed[0]?.id ?? 'default'
}This removes the inline early-return and the mutable preferredWorkspaceId = null trick while preserving the same behavior (cached-if-managed, else first managed, else default).
- Add a small unit test matrix: cached valid / cached present-but-not-manager / cached missing / empty list / no managers / manager without id.
Summary of most important fixes
- Pure function over direct
localStorageaccess (testability/SSR safety). - Remove the mid-loop early return — restructure for clarity.
- Confirm all call sites updated for the new signature.
| const selectedWorkspaceId = ref(getInitialWorkspaceId(user.userInfo?.workspace_list)) | ||
| const workspaceOptions = ref<WorkspaceItem[]>([]) | ||
| const loadingView = ref(false) | ||
|
|
There was a problem hiding this comment.
Here are my observations:
1. Behavior change risk (most important)
The refactor drops the persisted localStorage value (ADMIN_STORAGE_KEY.WORKSPACE_ID) as an input to getInitialWorkspaceId. Previously, a user's last-selected workspace would be restored on page load. Now the initial selection will always be derived from user.userInfo?.workspace_list. Confirm this is intentional; if persistence is still desired, pass the stored ID through (or let getInitialWorkspaceId read storage), otherwise users lose their previous selection after refresh.
2. Function signature consistency
Ensure getInitialWorkspaceId has actually been updated to accept a single argument. If the function still expects two parameters, the call is fine but the first param becomes undefined for the storage key — verify the new definition matches this call site (and any other call sites).
3. Fallback / edge cases
- What happens when
user.userInfo?.workspace_listisundefined, empty, or lacks the previously selected ID? ConfirmgetInitialWorkspaceIdreturns a safe default (e.g., first workspace ornull). - If it returns
null/empty, downstream code usingselectedWorkspaceIdshould handle that gracefully.
4. Removal of the import
Since ADMIN_STORAGE_KEY is no longer imported here, make sure nothing else in this file references it (looks clean in the diff) and that clearing the persisted key elsewhere isn't now orphaned/dead logic. Also check whether the constants module still needs WORKSPACE_ID for other consumers.
5. Reactivity of user info
user.userInfo?.workspace_list is read once at setup. If userInfo loads asynchronously, the initial selectedWorkspaceId may compute before data arrives. Consider guarding with a watcher or initializing after user info is ready.
6. Type safety (minor)
getInitialWorkspaceId(user.userInfo?.workspace_list) — ensure the function signature reflects a possibly-undefined list, so TS doesn't silently accept mismatched types.
Optimization suggestions
- If losing persistence is unintended, prefer passing
localStorage.getItem(ADMIN_STORAGE_KEY.WORKSPACE_ID)as an optional second param rather than embedding storage access inside the helper (keeps the helper pure/testable). - Add/update unit tests covering: no persisted value, invalid persisted ID, empty workspace list, and successful restore — to lock in the new expected behavior.
- Consider a small comment noting why persistence was removed, to prevent regression.
Overall the change itself is clean; the main concern is the dropped localStorage-backed selection — please verify that's deliberate.
| const selectedWorkspaceId = ref(getInitialWorkspaceId(user.userInfo?.workspace_list)) | ||
| const workspaceOptions = ref<WorkspaceItem[]>([]) | ||
|
|
||
| function handleWorkspaceSelect(workspace: WorkspaceItem) { |
There was a problem hiding this comment.
Code Review
1. Removed import — make sure it's truly unused
ADMIN_STORAGE_KEY is removed, but also verify:
localStorageisn't used elsewhere in the file.- No other references to
ADMIN_STORAGE_KEYremain (the diff only shows one usage site, but double-check).
2. Behavior change in getInitialWorkspaceId signature
The call changed from:
getInitialWorkspaceId(storedId, workspaceList)to:
getInitialWorkspaceId(workspaceList)Potential issues:
- Loss of persistence preference: Previously, the app restored the last-selected workspace from
localStorage. Now it relies solely onuser.userInfo?.workspace_list. If that function now just picks a default (e.g., first item), users lose their previous selection on reload — is that intentional? - Ordering dependency: The ref initialization runs at setup time. If
user.userInfois populated after this runs (e.g., async fetch),workspace_listmay beundefined, producing an incorrect/empty initial value that won't reactively update. Consider computing/watching instead of a one-shotref(). - Verify the new implementation: Confirm
getInitialWorkspaceId(workspaceList)handlesundefined/empty arrays gracefully and has predictable fallback behavior.
3. Reactive staleness
const selectedWorkspaceId = ref(getInitialWorkspaceId(user.userInfo?.workspace_list))Since this is evaluated once, if user loads asynchronously the initial ID can become stale. Prefer:
watch(() => user.userInfo?.workspace_list, (list) => {
if (list?.length) selectedWorkspaceId.value = getInitialWorkspaceId(list)
}, { immediate: true })…unless user info is guaranteed available before component setup.
4. Persistence / UX regression
If you no longer read from storage here, ensure something still writes the selected workspace (in handleWorkspaceSelect) so cross-session selection is preserved — otherwise this is an unintended UX regression.
5. Optimization notes
- Keep
handleWorkspaceSelectupdating both state and any persisted store consistently. - If
workspaceOptionsderives fromuser.userInfo.workspace_list, considercomputedinstead of a manually assignedref. - Minor: ensure the removed blank line/formatting aligns with lint rules (trailing comma style is consistent — good).
Summary
The edit is syntactically fine, but it changes persistence semantics. Confirm that (a) dropping localStorage restoration is intended, (b) the new getInitialWorkspaceId handles async/undefined input safely, and (c) selected workspace is still persisted somewhere for continuity.
refactor: centralize initial workspace selection for system pages